import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 38917
 * Date: 2025-03-29
 * Time: 19:36
 */
public class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        int length = nums.length;
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(nums);
        for(int i = 0;i < length;){
            int target = -nums[i],left = i + 1,right = length - 1;
            if(nums[i] > 0) break;
            while(left < right){
                if(nums[left] + nums[right] == target){
                    List<Integer> cur = new ArrayList<>();
                    cur.add(nums[left]);
                    cur.add(nums[right]);
                    cur.add(nums[i]);
                    result.add(cur);
                    left++;
                    right--;
                    while(left < right && nums[left] == nums[left - 1]) left++;
                    while(left < right && nums[right] == nums[right + 1]) right--;
                }else if(nums[left] + nums[right] < target){
                    left++;
                }else{
                    right--;
                }
            }
            do i++;
            while(i < length && nums[i] == nums[i - 1]);
        }
        return result;
    }

    public static void main(String[] args) {
        Solution s = new Solution();
        List<List<Integer>> result = s.threeSum(new int[]{-1,0,1,2,-1,-4});
        for(List<Integer> cur : result){
            for(Integer i : cur){
                System.out.print(i + " ");
            }
            System.out.println();
        }
    }
}